package array

import (
	"fmt"
	"sort"
)

func largestSumAfterKNegations(nums []int, k int) int {

	count := 0

	sort.Ints(nums)
	index := 0
	for index < len(nums) {
		if nums[index] >= 0 {
			break
		}
		index++
	}

	if index == 0 {
		if k%2 == 1 {
			nums[index] = -nums[index]
		}
		return getSum(nums)
	}

	for i := 0; i < index && count < k; i++ {
		nums[i] = -nums[i]
		count++
	}

	if count < k {
		sort.Ints(nums)
		left := k - count
		if left%2 == 1 {
			nums[index] = -nums[index]
		}
	}

	fmt.Println(nums)

	return getSum(nums)

}

func getSum(nums []int) int {
	res := 0
	for _, v := range nums {
		res += v
	}
	return res
}
